﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynamicallyBuildUDFBasedOnSchema
{
	class PopulateSQL
	{
		public static void CreateAssembly(string dbServer, string dbName)
		{
			string connectionString = string.Format("Data Source = {0}; Initial Catalog = {1}; Integrated Security=SSPI", dbServer, "master");
			using (SqlConnection conn = new SqlConnection(connectionString))
			{
				try
				{
					conn.Open();
				}
				catch (SqlException ex)
				{
					Console.WriteLine(ex.Message);
					Console.WriteLine(conn.State);
					return;
				}

				if (conn.State == ConnectionState.Open)
				{
					Console.WriteLine(getWindowsDirectory(conn));
				}
			}
		}

		static string getHexString(Stream dll)
		{
			StringBuilder builder = new StringBuilder();
			builder.Append("0x");

			int currentByte = dll.ReadByte();
			while (currentByte > -1)
			{
				builder.Append(currentByte.ToString("X2", CultureInfo.InvariantCulture));
				currentByte = dll.ReadByte();
			}

			return builder.ToString();
		}

		static string getWindowsDirectory(SqlConnection conn)
		{
			string sqlText = @"SELECT value_data FROM sys.dm_server_registry WHERE registry_key = 'HKLM\Software\Microsoft\Windows NT\CurrentVersion' AND value_name = 'SystemRoot'";
			using (SqlCommand cmd = new SqlCommand(sqlText, conn))
			{
				cmd.CommandType = CommandType.Text;
				SqlDataReader r = cmd.ExecuteReader();

				while (r.Read())
				{
					return r.GetString(0);
				}

				r.Close();
			}

			return @"C:\Windows2";
		}
	}
}
